package cn.vihub.controller;

import cn.vihub.param.ShopRoleParam;
import cn.vihub.pojo.ShopRole;
import cn.vihub.service.ShopRoleService;
import cn.vihub.service.ShopRoleToMenuService;
import cn.vihub.service.ShopUserToRoleService;
import cn.vihub.utils.Result;
import com.baomidou.mybatisplus.core.metadata.IPage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("shop-user/role")
@Slf4j
public class RoleController {

    @Autowired
    private ShopRoleService shopRoleService;

    @Autowired
    private ShopUserToRoleService shopUserToRoleService;

    @Autowired
    private ShopRoleToMenuService shopRoleToMenuService;

    @GetMapping("list")
    public Result<IPage<ShopRole>> list(ShopRoleParam shopRoleParam){
        return Result.success(shopRoleService.selectByPage(shopRoleParam));
    }

    /**
     * 角色添加编辑
     * @param shopRoleParam
     * @return
     */
    @PostMapping("save")
    public Result<Boolean> save(@RequestBody ShopRoleParam shopRoleParam){

        ShopRole shopRole = new ShopRole();
        BeanUtils.copyProperties(shopRoleParam, shopRole);

        log.info("test{}",123123213);
        return shopRoleService.saveOrUpdate(shopRole)?Result.success():Result.error();
    }

    /**
     * 角色删除
     * @param id
     * @return
     */
    @DeleteMapping("delete/{id}")
    public Result<Boolean> delete(@PathVariable("id") Integer id){

        // 检查角色下是否存在关联用户
        shopUserToRoleService.isUserByRoleId(id);

        if (shopRoleService.removeById(id)){

            // 删除角色和菜单关联的数据
            shopRoleToMenuService.removeByRoleId(id);

            return Result.success();
        }else {
            return Result.error();
        }

    }

    /**
     * 角色绑定菜单
     */
    @PostMapping("bindMenu")
    public Result<Boolean> bindMenu(@RequestBody ShopRoleParam shopRoleParam){
        return Result.success(shopRoleService.bindMenu(shopRoleParam));
    }
























}
